#!/bin/python
# -*- coding: utf8 -*-


from lib.common.aliyun_ots import cli, Condition, INF_MIN, INF_MAX
import lib.common.func as com_func
import lib.common.aliyun_redis

ots = cli()
redis = lib.common.aliyun_redis.cli()

TABLE = 'prize'
TABLE_CACHE = 'prize_cache'
TABLE_LIST_CACHE = 'prize_list_cache'


def add_prize(exchange_code , attr={}):
    ts = lib.common.func.get_ts()
    pk = {
        'exchange_code': str(exchange_code),
    }
    attr['ctime'] = ts
    attr['mtime'] = ts
    code = ots.put_row(TABLE, Condition('EXPECT_NOT_EXIST'), pk, attr)
    if code == 0:
        clear_prize_list_cache()
    return code


def update_prize(exchange_code, attr={}):
    ts = lib.common.func.get_ts()
    pk = {
        'exchange_code': str(exchange_code),
    }
    attr['mtime'] = ts
    code = ots.update_row(TABLE, Condition('EXPECT_EXIST'), pk, {'put': attr})
    if code == 0:
        clear_prize_cache(exchange_code)
        clear_prize_list_cache()
    return code


def delete_prize(exchange_code):
    pk = {
        'exchange_code': str(exchange_code),
    }
    code = ots.delete_row(TABLE, Condition('IGNORE'), pk)
    if code == 0:
        clear_prize_cache(exchange_code)
        clear_prize_list_cache()
    return code


def get_prize(exchange_code):
    data = get_prize_cache(exchange_code)
    if data is None:
        data = get_prize_ots(exchange_code)
        if len(data) > 0:
            set_prize_cache(exchange_code, data)
    else:
        data = lib.common.func.deserialize(data)
    return data


def get_prize_ots(exchange_code):
    pk = {
        'exchange_code': str(exchange_code),
    }
    data = ots.get_row(TABLE, pk, [])
    return data


def get_prize_list():
    data_list = get_prize_list_cache()
    if data_list is None:
        data_list = get_prize_list_ots()
        if len(data_list) > 0:
            set_prize_list_cache(data_list)
    else:
        data_list = lib.common.func.deserialize(data_list)

    return data_list


def get_prize_list_ots():
    pk_b = {
        'exchange_code': INF_MIN,
    }
    pk_e = {
        'exchange_code': INF_MAX,
    }
    data_list = []
    while pk_b is not None:
        rows, pk_b = ots.get_range(TABLE, 'FORWARD', pk_b, pk_e, [])
        if len(rows) > 0:
            data_list.extend(rows)
    return data_list


def set_prize_cache(exchange_code, data):
    redis.set('{}-{}'.format(TABLE_CACHE, exchange_code), lib.common.func.serialize(data))


def get_prize_cache(exchange_code):
    return redis.get('{}-{}'.format(TABLE_CACHE, exchange_code))


def clear_prize_cache(exchange_code):
    redis.delete('{}-{}'.format(TABLE_CACHE, exchange_code))


def set_prize_list_cache(data):
    redis.set('{}'.format(TABLE_LIST_CACHE), lib.common.func.serialize(data))


def get_prize_list_cache():
    return redis.get('{}'.format(TABLE_LIST_CACHE))


def clear_prize_list_cache():
    redis.delete('{}'.format(TABLE_LIST_CACHE))


